import React from "react"
import {AutoComplete, Input, Space, Typography} from "antd"
const {Text} = Typography


export default class Searchbar extends React.Component {

    constructor(props){
        super(props)

        this.state = {
            searching: false,
            value: "",
            options: []
        }

    }

    onChange(value) {
        this.setState({
            value: value
        })
    }

    onSelect(value, option) {
        this.setState({
            value: ""
        })
    }

    onSearch(q) {

        fetch("/api/search/?q=" + q) 
        .then(response => response.json())
        .then( message => {

            if (message.code != 0) {
                // handler errors
                return
            }

            if (message.data == null) return

            let results = message.data.map(m=>({
                label: (
                    <div>
                        <Text strong style={{ display: "block" }}>{ m.name }</Text>
                        <Text type="secondary" style={{ display: "block", fontSize: 10 }}>{ m._id_ }</Text>
                    </div>
                ),
                value: `${m._id_}`

            }));

            this.setState({
                searching: false,
                options: results
            })
        })
    }

    render() {

        return (
            <AutoComplete style={{ width: 220, margin: "6px 0", borderRadius: 0 }}
                options={ this.state.options }
                value={ this.state.value }
                onSearch={(value) => this.onSearch(value)}
                onChange={(value)=>this.onChange(value)}
                onSelect={(value, option) => this.onSelect(value, option)}
            >

                <Input.Search size="small" placeholder="请输入搜索关键词" ></Input.Search>
            </AutoComplete>

        )
    }


}